#include <iostream>
#include "ReconstructByKinectCommon.h"

using namespace xn;
using namespace std;

//---------------------------------------------------------------------------
// Defines
//---------------------------------------------------------------------------
#define KINECT_CONFIG_PATH "..\\Data\\KinectConfig.xml"

//---------------------------------------------------------------------------
// Globals
//---------------------------------------------------------------------------
std::vector< SensorDataInput* > g_pSensorInput;
std::vector< SensorDataFileOutput* > g_pOutput;

//---------------------------------------------------------------------------
// Code
//---------------------------------------------------------------------------
void clean ();

// exe file1 file2 ...
int main(int argc, char* argv[])
{
	if (argc <= 2) {
		printf ("Command line argument error.\n");
		return -1;
	}
	try {
		OpenNIContextManager contextManager;
		for (int i = 1; i < argc; ++i) {
			SensorDataInput *pSensorInput = contextManager.createSensor (std::string ("Sensor ") + (char)('0' + i));
			if (pSensorInput == NULL)
				throw std::exception ("Fail to create sensor");
			SensorDataFileOutput *pOutput = new SensorDataFileOutput (argv[i], *pSensorInput);
			g_pSensorInput.push_back (pSensorInput);
			g_pOutput.push_back (pOutput);
		}

		contextManager.start ();
		while (true) {
			contextManager.update ();
			for (int i = 0; i < g_pSensorInput.size (); ++i) {
				if (!g_pSensorInput[i]->getNewFrame ()) {
					clean ();
					exit (-1);
				}
				g_pOutput[i]->writeFrame ();
				g_pSensorInput[i]->showData ("Kinect Data Exporter - ");
			}
			if (cvWaitKey (1) == 27)
				break;
		}
	} catch (...) {
		printf ("Exception caught\n");
	}
	return 0;
}

void clean ()
{
	for (int i = 0; i < g_pSensorInput.size (); ++i) {
		delete g_pSensorInput[i];
		delete g_pOutput[i];
	}
}